package com.zhaokuner.springboot.refresh;

import com.zhaokuner.springboot.model.AfterRunnerModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Description:刷新后的处理
 * <p>
 * Copyright: 2018-现在 北京掌通未来科技有限公司
 * <p>
 *
 * @author 赵希坤 zhaoxikun
 * @date 2020/7/28 08:58
 */
public class RefreshAfterRunner {
    /**
     * 多个实现
     */
    private List<Runner> runnerList = new ArrayList<>();
    /**
     * 单线程
     */
    private ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());


    public void addRunner(Runner runner) {
        if (null != runner) {
            runnerList.add(runner);
        }
    }

    void run(boolean result, String msg, Exception e) {
        if (null != runnerList) {
            for (Runner runner : runnerList) {
                AfterRunnerModel temp = new AfterRunnerModel();
                temp.setResult(result);
                temp.setMsg(msg);
                temp.setE(e);
                executor.execute(() -> {
                    runner.run(temp);
                });
            }
        }

    }


    /**
     * 执行接口
     */
    public interface Runner {
        /**
         * run
         *
         * @param model 参数
         */
        void run(AfterRunnerModel model);

        /**
         * 数据
         *
         * @return
         * @throws Exception
         */
        default HashMap<String, Object> map() throws Exception {
            return new HashMap<>(8);
        }
    }

}
